<?php

namespace App\Http\Controllers\Wechat;

use App\Models\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use Illuminate\Http\Request;

class ServerController {
    public function server(){
        try {
            $app = Factory::officialAccount(\Config::get('wechat'));
            $app->server->push(function ($message) use ($app) {
                \Log::debug($message);
                global $appId;
                switch ($message['MsgType']) {
                    case 'event':
                        switch ($message['Event']) {
                            case 'unsubscribe':
                                break;
                            case 'subscribe':
                                global $wechatName;
                                $wechatText = <<<EOF
                                aaa
EOF;

                                $openid = $message['FromUserName'];
                                $ticker = isset($message['Ticket'])?$message['Ticket']:null;
                                $userInfo = User::where('wx_openid', $openid)->first();
                                if($userInfo && (!isset($userInfo->father_id) || $userInfo->father_id == 0) && !empty($ticker)) {
                                    $agentInfo = User::where('ticket', $ticker)->where('is_agent', 1)->first();
                                    if (!$agentInfo) {
                                        \Log::error("上级代理ID没有找到；上级ID:{$agentInfo->id},用户ID:{$agentInfo->id}");
                                    } else {
                                        if (
                                            \App\Models\User::where('id', $userInfo->id)
                                                ->where('father_id', 0)
                                                ->update([
                                                    'father_id' => $agentInfo->id,
                                                ]) === false
                                        ) {
                                            \Log::waring("更新father_id失败；上级ID:{$agentInfo->id},用户ID:{$userInfo->id}");
                                        } else {
                                            $wechatServerController = new ServerController();
                                            \Log::debug($appId);
                                            $tempid = 'T5aGjrCD9MUZRGgk09lQuzcIqEeH-01JSj4ONJ52tzY';
                                            $tempData = [
                                                'first' => "恭喜您有新的下级加入",
                                                'keyword1' => $userInfo->id,
                                                'keyword2' => date('Y-m-d H:i:s', time()),
                                                'keyword3' => $userInfo->nick_name
                                            ];
                                            $tempUrl = env('APP_URL') . "/api/wechat/login?appid={$appId}&redirect=center";
                                            $wechatServerController->sendTempMsg($appId, $agentInfo->wx_openid, $tempid, $tempData, $tempUrl);
                                        }
                                    }
                                }
                                return $wechatText;
                                break;
                            case 'CLICK':
                                switch ($message['EventKey']){
                                    case 'SHARE_CODE':
                                        $openid = $message['FromUserName'];
                                        $userInfo = User::where('wx_openid', $openid)->where('is_agent', 1)->first();
                                        if(!$userInfo){
                                            return '您还不是代理,请先点击菜单"个人中心"申请成为代理';
                                        }
                                        $this->sendStaff($openid, 'text', '正在生成中....');
                                        fastcgi_finish_request();
                                        $filePath = public_path('qrcode/'.$userInfo->id.'.png');
                                        $qrCodeData = $app->qrcode->temporary($openid, 6*24*3600);
                                        if(isset($qrCodeData['ticket'])){
                                            if(User::where('wx_openid', $openid)->update(['ticket' => $qrCodeData['ticket']]) === false){
                                                $this->sendStaff($openid, 'text', '生成失败，重新获取');
                                            }else {
                                                $qrCodeUrl = $app->qrcode->url($qrCodeData['ticket']);
                                                $qrCodeContent = file_get_contents($qrCodeUrl);
                                                file_put_contents($filePath, $qrCodeContent);
                                                $result = $app->media->uploadImage($filePath);
                                                \Log::debug($result);
                                                if (isset($result['media_id'])) {
                                                    $this->sendStaff($openid, 'img', $result['media_id']);
                                                }
                                            }
                                        }else{
                                            $this->sendStaff($openid, 'text', '生成失败，重新获取');
                                        }
                                        break;
                                }
                                break;
                        }
                        break;
                    case 'text':
                        if (preg_match('/.*找(.*)/i', $message['Content'], $match)) {
                            if (empty($match[1])) {
                                return "您要找什么?";
                            } else {
                                $jidi = new Jidi();
                                $accessToken = $jidi->getToken();
                                $products = curlGet($jidi->getProductsUrl() . "?token={$accessToken}&k={$match[1]}&per=1&page=1&sort=3");
                                $products = json_decode($products);
                                if (isset($products->proList) && !empty($products->proList->data)) {
                                    $product = $products->proList->data[0];
                                    $data = [
                                        'title' => "您要得{$match[1]}找到了",
                                        'description' => '赶快点我查看更多吧!',
                                        'image' => $product->pic,
                                        'url' => env('WEB_URL') . "/taoke?searchKey={$match[1]}",
                                    ];
                                    $newsItem = new NewsItem($data);
                                    $message = new News([$newsItem]);
                                    return $message;
                                }

                                $url = env('APP_URL') . "/api/wechat/login?appid={$appId}&redirect=index";
                                return "您要找的$match[1]没有找到，建议再重新更换搜索的内容；比如'找面膜'等！也可以去{$url}/taoke找找，可能由您喜欢的";
                            }
                        } else if (preg_match('/.*优惠券.*/i', $message->Content, $match)) {
                            return "亲，点击进入公众号底部菜单“领优惠券”，您就能搜索任何你想买的东西啦，都有优惠券的哦~";
                        } else {
                            return "亲，很抱歉，我没明白您的意思。24小时内会有人工客服来回答您的问题。如果想找优惠券，请点击进入公众号底部菜单“领优惠券”，就能搜索任何您想买的东西啦，都是有优惠券的哦~";
                        }
                        break;
                        break;
                    case 'image':
                        return '收到图片消息';
                        break;
                    case 'voice':
                        return '收到语音消息';
                        break;
                    case 'video':
                        return '收到视频消息';
                        break;
                    case 'location':
                        return '收到坐标消息';
                        break;
                    case 'link':
                        return '收到链接消息';
                        break;
                    // ... 其它消息
                    default:
                        return '收到其它消息';
                        break;
                }
            });

            return $app->server->serve();
        }catch (\Exception $exception){
            \Log::error($exception);
        }
    }

    /**
     * 设置菜单
     */
    public function setMenu(Request $request){
        $appId = $request->get('appid');

//        $wechatBlock = new Wechat();

//        $menuData = $wechatBlock->getWechatMenuByAppId($appId);

//        $menu = json_decode($menuData->menu, true);

        $menu = [
            [
                "type" => "view",
                "name" => "聚宝阁装修",
                "url"  => "http://fitment.guoxiaoge.cn/api/wechat/login?appid=wx91fad304a48505cd&redirect=index"
            ],
        ];
        $config = \Config::get('wechat.official_account.default');
        $app = Factory::officialAccount($config);
        $app->menu->create($menu);
    }

    /**
     * 发送客服消息
     */
    public function sendStaff($openId , $type  , $content){
        try {
            $message = '';

            if ($type == 'text') {
                $message = new Text($content);
            } elseif ($type == 'img') {
                $message = new Image($content);
            } elseif ($type == 'news') {
                $newsItem = new NewsItem($content);
                $message = new News([$newsItem]);
            }

            if (!empty($message)) {
                $app = Factory::officialAccount(\Config::get('wechat'));
                $staff = $app->customer_service; // 客服管理
                return $staff->message($message)->to($openId)->send();
            } else {
                return false;
            }
        }catch (\Exception $exception){
            \Log::debug($exception);
        }
    }

    //获取微信js sdk
    /**
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          'apis' : str,
     *          'debug' : true/false   //是否开启调试
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' => xxx     返回数据
     *      ]
     *   ]
     */
    //参数1, api参数  2,是否开启调试 3不知道, 4是否返回json格式
    public function getJsSdk(Request $request)
    {
        $apis = $request->input('apis');
        if ($apis) {
            $apis_arr = explode(',', $apis);
        } else {
            $apis_arr = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo'];
        }

        $app = Factory::officialAccount(\Config::get('wechat'));
        $js = $app->jssdk;

        $debug = false;
        if ($request->has('debug')) {
            $debug = $request->input('debug');
        }

        if ($request->has('url')) {
            $js->setUrl($request->get('url'));
        }
        $config = $js->buildConfig($apis_arr, $debug, $beta = false, $json = true);
        if (!empty($config)) {
            return response()->json($config);
        } else {
            return response()->json(['error' => '没有数据']);
        }

    }

    public function login(Request $request){
        $config = \Config::get('wechat.official_account.default');
        \Log::debug($config);
        $config['oauth']['callback'] .= '?'.http_build_query($request->all());
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }

    public function getWechatConfig($appId){
        $config = WechatConfig::where('app_id', $appId)->first();
        if($config){
            $wechatConfig = [
                'app_id'                => $config->app_id,
                'secret'                => $config->secret,
                'token'                 => $config->token,
                'aes_key'               => $config->aes_key,
                'oauth'                 => [
                    'only_wechat_browser'   => $config->oauth_only_wechat_browser,
                    'scopes'                => $config->oauth_scopes,
                    'callback'              => $config->oauth_callback
                ],
            ];

            return $wechatConfig;
        }else{
            return [];
        }
    }

    public function sendTempMsg($appId, $openId, $tempid, $data=[], $url){
        try {
            $app = Factory::officialAccount($this->getWechatConfig($appId));
            return $app->template_message->send([
                'touser' => $openId,
                'template_id' => $tempid,
                'url' => $url,
                'data' => $data,
            ]);
        }catch (\Exception $exception){
            \Log::error($exception);
        }
    }
}